//
//  UIButton+SingleClick.swift
//  OneDay
//
//  Created by cheng xi on 2016/9/22.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit
import ObjectiveC

private var oldTimeTag:UInt8 = 0
private var interfTag:UInt8 = 2
private var hasAddTargetTag:UInt8 = 3
private var singleClickTag:UInt8 = 4

private let DEFAULT_INTERF:TimeInterval = 0.6

extension UIButton {
  
  var _oldTime:TimeInterval {
    
    get{
      
      if let oldTime =  objc_getAssociatedObject(self, &oldTimeTag) as? TimeInterval {
        return oldTime
      }
      return 0
    }
    
    set(newValue){
      
      objc_setAssociatedObject(self, &oldTimeTag, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
      
    }
    
  }
  
  
  var _interf:TimeInterval {
    
    get{
      
      if let interf =  objc_getAssociatedObject(self, &interfTag) as? TimeInterval {
        return interf
      }
      return DEFAULT_INTERF
    }
    
    set(newValue){
      
      objc_setAssociatedObject(self, &interfTag, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
      
    }
    
  }
  
  var _hasAddTarget:Bool {
    
    get{
      if let hasTargetFlag = objc_getAssociatedObject(self, &hasAddTargetTag) as? Bool {
        return hasTargetFlag
      }
      return false
    }
    
    set(newValue){
      
      objc_setAssociatedObject(self, &hasAddTargetTag, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
      
    }
    
  }
  
  var _singleClick:ClickListener? {
    
    get{
      return objc_getAssociatedObject(self, &singleClickTag) as? ClickListener
    }
    
    set(newValue){
      
      if !self._hasAddTarget {
        self.addTarget(self, action: #selector(UIButton.clickBtn), for: .touchUpInside)
        self._hasAddTarget = true
      }
      
      objc_setAssociatedObject(self, &singleClickTag, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
      
    }
    
  }
  
  @objc fileprivate func clickBtn(){
    let currentTime = CACurrentMediaTime()
    if (currentTime - self._oldTime > _interf) {
      _singleClick?._singleClick?()
      _oldTime = currentTime
    }
  }
  
  
  func fixSingleClickListener( _ listener: ClickListener?) {
    self.fixSingleClickListener(0.6, listener)
  }
  
  func fixSingleClickListener(_ interf: TimeInterval , _ listener: ClickListener?) {
    self._interf = interf
    self._singleClick = listener
  }
}

open class ClickListener:NSObject {
  
  var _singleClick:(()->Void)? = nil
  
  init(block:@escaping (()->Void)) {
    self._singleClick = block
  }
  
}
